<?php
/**
 * @author shutyuka@gmail.com
 * @modified 2011-02-20
 */
class Users
{
	const SECRET_KEY = '@4!@#$%@';
	
	static public $STATUS_UNACTIVE = 0;
	
	static public $STATUS_ACTIVATE = 10;
	
	static public $STATUS_STAFF = 30;
	
	static public $STATUS_DEL = 40;
	
	static public $TABLE_NAME="users";
	
	static public function GenPassword($p) {
		return md5($p . self::SECRET_KEY);
	}

	static public function Create($user_row) {
		$user_row['password'] = self::GenPassword($user_row['password']);
		$user_row['create_time'] = $user_row['login_time'] = time();
		$user_row['ip'] = Utility::GetRemoteIp();
		$user_row['secret'] = md5(rand(1000000,9999999).time().$user_row['email']);
		$user_row['id'] = DB::Insert(self::$TABLE_NAME, $user_row);
		if( $user_row['id'] == 1 ){
			for($index = 10; $index < 100; $index+=1){
				OauthLimit::Create($user_row['id'], $index);
			}
		}
		return $user_row['id'];
	}

	static public function GetUser($user_id) {
		if (!$user_id) 
			return array();
		return Table::Fetch(self::$TABLE_NAME, $user_id);
	}
	
	static public function GetUserByEmail($email) {
		if (!$email) 
			return array();
		return Table::Fetch(self::$TABLE_NAME, $email, 'email');
	}
	
	static public function GetUserByVerifyCode($verify_code) {
		if (!$verify_code) 
			return array();
		return Table::Fetch(self::$TABLE_NAME, $verify_code, 'secret');;
	}

	static public function GetLoginCookie($cname='ru') {
		$cv = cookieget($cname);
		if ($cv) {
			$zone = base64_decode($cv);
			$p = explode('@', $zone, 2);
			return DB::GetTableRow(self::$TABLE_NAME, array(
				'id' => $p[0],
				'password' => $p[1],
			));
		}
		return Array();
	}

	static public function Modify($user_id, $newuser=array()) {
		if (!$user_id) return;
		/* tuan db */
		$newuser['password'] = self::GenPassword($newuser['password']);
		Table::UpdateCache(self::$TABLE_NAME, $user_id, $newuser);
	}

	static public function GetLogin($email, $unpass, $en=true) {
		if($en){
			$password = self::GenPassword($unpass);
		}
		$field = strpos($email, '@') ? 'email' : 'username';
		$user = DB::GetTableRow(self::$TABLE_NAME, array(
					$field => $email,
					'password' => $password,
		));
		if ($user){
			return $user;
		}
		return array();
	}
	
	static public function ActiveUser($user){
		//Logs::setLog("active||error===get-null||=".$verify_code);
		$newVerifyCode = md5(rand(1000000,9999999).time().$user['email']);
		Table::UpdateCache(self::$TABLE_NAME, $user['id'], array(
		'status' => self::$STATUS_ACTIVATE, 
		'secret' => $newVerifyCode)
		);
		return ;
	}
	
	static public function GetAll(){
		$oc = array('status<='.self::$STATUS_ACTIVATE);
		$all = DB::LimitQuery(self::$TABLE_NAME, array(
					'condition' => $oc,
					'order' => 'ORDER BY id ASC'
				));
		return $all;
	}
}
